﻿using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections.Generic;
using XLua;
[LuaCallCSharp]
[CSharpCallLua]
public class SocketManager
{
    private static IPAddress ip = IPAddress.Parse("127.0.0.1");
    private static IPEndPoint point = new IPEndPoint(ip, 8080);
    private static List<Thread> useThread = new List<Thread>();
    [CSharpCallLua]
    public delegate void ReciveDelegate(int type, string obj);
    public static ReciveDelegate reciveDelegate = null;
    //发送消息，lua调用
    public static void Send(int type, string msg)
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(point);
        if (useThread.Count == 0)
        {
            Thread thread = new Thread(Recive);
            thread.Start(client);
        }
        else
        {
            Thread thread = useThread[0];
            useThread.RemoveAt(0);
            thread = new Thread(Recive);
            thread.Start(client);
        }
        byte[] data= MessageHandler.get.GetMessage(type, msg);
        client.Send(data);
    }
    //接收消息
    private static void Recive(object obj)
    {
        try
        {
            Socket client = obj as Socket;
            byte[] data = new byte[1024];
            while (true)
            {
                int count = client.Receive(data);
                if (count == 0)
                {
                    CloseSocket(client);
                    Log.LogError("接收到服务器的空消息，请查看！");
                    break;
                }
                MessageHandler.get.Recive(count, data);
                CloseSocket(client);
                break;
            }
        }
        catch
        {
        }
    }
    //关闭链接
    public static void CloseSocket(Socket client)
    {
        client.Shutdown(SocketShutdown.Both);
        client.Close();
        client = null;
        useThread.Add(Thread.CurrentThread);
        Thread.CurrentThread.Abort();
    }
}
